<template>
  <div class="login_container">
    <img src="@/images/login_containerback.png" class="login_containerback" />
    <div class="login_title"> {{ title }} <span>学生端</span> </div>
    <div class="login_form">
      <div class="login_formcont">
        <div class="login_formtitle">登录</div>
        <el-form
          ref="loginForm"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
          autocomplete="on"
          label-position="left"
        >
          <el-form-item prop="username">
            <el-input
              ref="username"
              v-model="loginForm.username"
              size="large"
              placeholder="请输入用户名"
              name="username"
              type="text"
              tabindex="1"
              autocomplete="on"
            >
              <i slot="prefix" class="el-icon-user-solid login_formicon"></i>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              ref="password"
              v-model="loginForm.password"
              size="large"
              placeholder="请输入密码"
              name="password"
              tabindex="2"
              autocomplete="on"
              show-password
              @keyup.enter.native="handleLogin"
            >
              <i slot="prefix" class="el-icon-lock login_formicon"></i>
            </el-input>
          </el-form-item>
          <el-button
            :loading="loading"
            type="primary"
            class="login_formbtn"
            @click.native.prevent="handleLogin"
            >登录</el-button
          >
        </el-form>
        <div class="login_toResign" @click="openAdd"> 注册 </div>
      </div>
    </div>
    <div class="login_bottom">
      <img src="@/images/login_bottom.png" />山东中飞科技有限公司 | 研发
    </div>
    <el-dialog
      title="注册"
      center
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :append-to-body="true"
      :visible.sync="resignDialog"
      width="520px"
    >
      <el-form
        :model="addForm"
        :rules="rules"
        ref="addForm"
        label-width="110px"
        style="width: calc(100% - 30px)"
      >
        <el-form-item label="姓名" prop="studentName">
          <el-input
            placeholder="请输入姓名"
            v-model="addForm.studentName"
            maxlength="20"
            style="width: 100%"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select
            v-model="addForm.sex"
            placeholder="请选择性别"
            style="width: 100%"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择班级" prop="organizationId">
          <el-cascader
            v-model="addForm.organizationIds"
            :options="organizations"
            @change="addOrgChange"
            placeholder="请选择班级"
            style="width: 100%"
            :props="classProps"
            :show-all-levels="false"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="学号" prop="studentNo">
          <el-input
            placeholder="请输入学号"
            v-model="addForm.studentNo"
            maxlength="50"
            style="width: 100%"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            placeholder="请输入密码"
            v-model="addForm.password"
            maxlength="255"
            style="width: 100%"
            type="password"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="passwordcheck">
          <el-input
            placeholder="请确认密码"
            v-model="addForm.passwordcheck"
            maxlength="255"
            style="width: 100%"
            type="password"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetAdd">取 消</el-button>
        <el-button type="primary" @click="addStudent" :disabled="dataloading"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getStorageToken,
    setStorageToken,
    removeStorageToken,
  } from '@/utils/auth';
  import { register, organizationTree } from '@/api/login.js';
  import { login } from '@/api/login.js';
  export default {
    data() {
      var validatePass1 = (rule, value, callback) => {
        if (this.addForm.passwordcheck) {
          if (value !== this.addForm.passwordcheck) {
            callback(new Error('两次输入密码不一致!'));
          } else {
            callback();
          }
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (this.addForm.password) {
          if (value !== this.addForm.password) {
            callback(new Error('两次输入密码不一致!'));
          } else {
            callback();
          }
        }
      };
      return {
        title: window.config.VUE_TITLE,
        organizations: [],
        loginForm: {
          username: '',
          password: '',
        },
        loginRules: {
          username: [
            {
              required: true,
              trigger: 'blur',
              message: '请输入用户名',
            },
          ],
          password: [
            {
              required: true,
              trigger: 'blur',
              message: '请输入密码',
            },
          ],
        },
        loading: false,
        dataloading: false,
        resignDialog: false,
        classProps: {
          value: 'id',
          label: 'name',
        },
        options: [
          {
            value: 'M',
            label: '男',
          },
          {
            value: 'F',
            label: '女',
          },
        ],
        addForm: {
          sex: '',
          studentNo: '',
          studentName: '',
          password: '',
          passwordcheck: '',
          organizationId: '',
        },
        rules: {
          sex: [
            {
              required: true,
              message: '请选择性别',
              trigger: 'blur',
            },
          ],
          studentNo: [
            {
              min: 4,
              message: '学号最少是四位！',
              trigger: 'blur',
            },
            {
              required: true,
              message: '请输入学号',
              trigger: 'blur',
            },
          ],
          studentName: [
            {
              required: true,
              message: '请输入姓名',
              trigger: 'blur',
            },
          ],
          password: [
            {
              required: true,
              message: '请输入密码',
              trigger: 'blur',
            },
            {
              validator: validatePass1,
              trigger: 'blur',
            },
          ],
          passwordcheck: [
            {
              required: true,
              message: '请确认密码',
              trigger: 'blur',
            },
            {
              validator: validatePass2,
              trigger: 'blur',
            },
          ],
          organizationId: [
            {
              required: true,
              message: '请选择班级',
              trigger: 'blur',
            },
          ],
        },
      };
    },
    created() {
      this.getDeptList();
      if (getStorageToken()) {
        this.$router.push({
          name: 'index',
        });
      }
    },
    mounted() {
      if (this.loginForm.username === '') {
        this.$refs.username.focus();
      } else if (this.loginForm.password === '') {
        this.$refs.password.focus();
      }
    },
    methods: {
      getDeptList() {
        organizationTree({}).then(async (res) => {
          if (res.code == '200') {
            var organizations = this.getChildren(res.data);
            this.organizations = organizations;
          }
        });
      },
      getChildren(arrs) {
        arrs.map((item) => {
          if (item.children && item.children.length > 0) {
            this.getChildren(item.children);
          } else {
            item.children = null;
          }
        });
        return arrs;
      },
      openAdd() {
        this.resignDialog = true;
      },
      addOrgChange() {
        var organizationIdsLen = this.addForm.organizationIds.length;
        if (organizationIdsLen > 0) {
          this.addForm.organizationId =
            this.addForm.organizationIds[organizationIdsLen - 1];
        } else {
          this.addForm.organizationId = '';
        }
      },
      addStudent() {
        this.dataloading = true;
        setTimeout((_) => {
          this.dataloading = false;
        }, 1000);
        this.$refs.addForm.validate((valid) => {
          if (valid) {
            register(this.addForm).then(async (res) => {
              if (res.code == '200') {
                this.$message({
                  message: res.message,
                  type: 'success',
                });
                this.resetAdd();
              } else {
                this.$message({
                  message: res.message,
                  type: 'error',
                });
              }
            });
          }
        });
      },
      resetAdd() {
        this.addForm.organizationIds = [];
        this.$refs.addForm.resetFields();
        this.$nextTick(() => {
          this.$refs.addForm.clearValidate();
          this.resignDialog = false;
        });
      },
      handleLoginAuto() {
        login({
          username: this.addForm.studentNo,
          password: this.addForm.password,
        }).then((res) => {
          if (res.code == '200') {
            setStorageToken(res.data);
            this.$router.push({
              name: 'index',
            });
          } else {
            this.$message({
              message: res.message,
              type: 'error',
            });
          }
        });
      },
      handleLogin() {
        this.$refs.loginForm.validate((valid) => {
          if (valid) {
            login({
              username: this.loginForm.username,
              password: this.loginForm.password,
            }).then((res) => {
              if (res.code == '200') {
                setStorageToken(res.data);
                this.$router.push({
                  name: 'index',
                });
              } else {
                this.$message({
                  message: res.message,
                  type: 'error',
                });
              }
            });
          }
        });
      },
    },
  };
</script>
